package com.leyou.gateway.util;

import com.leyou.auth.inter.pojo.UserInfo;
import com.leyou.common.bean.Constant;
import com.leyou.common.bean.Result;
import com.leyou.common.bean.ResultCode;
import com.leyou.common.util.JsonUtils;
import com.leyou.common.util.StringUtil;
import com.leyou.user.inter.pojo.Permission;
import com.netflix.zuul.context.RequestContext;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author zqq
 * @ClassName AuthUtils
 * @Description: 权限判断工具
 * @date 2020/3/25-9:47
 */
public class AuthUtils {

    private final static PathMatcher MATCHER = new AntPathMatcher();

    public static void response(RequestContext context, ResultCode code){
        context.getResponse().setContentType("application/json");
        context.getResponse().setContentType("text/html;charset=UTF-8");
        context.setSendZuulResponse(false);
        context.setResponseBody(JsonUtils.serialize(Result.newFailure(code)));
        context.set("isSuccess", false);
    }

    public static boolean checkAuthorize(HttpServletRequest request,StringRedisTemplate redisTemplate, UserInfo userInfo){
        //解析角色
        List<String> roles = JsonUtils.parseList(userInfo.getRoles(), String.class);
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(Constant.KEY_AUTHORIZE_CODE);
        List<Permission> list = new ArrayList<>();
        Set<Object> keys = hashOps.keys();
        for (Object key : keys) {
            for (String role : roles) {
                if(key.toString().equals(role)){
                    //判断是否存在权限
                    if(hashOps.hasKey(role)){
                        String json = hashOps.get(role).toString();
                        if(StringUtil.isEmpty(json)){
                            List<Permission> permissions = JsonUtils.parseList(json, Permission.class);
                            if(permissions.size() > 0)
                                list.addAll(permissions);
                        }
                    }
                }
            }
        }
        if(list.size() == 0){
            return false;
        }
        String url = request.getRequestURI().substring(4);
        String method = request.getMethod();
        boolean bool = false;
        //判断是在权限中
        for (Permission permission : list) {
            if(MATCHER.match(permission.getUrl(),url) && permission.getMethod().equalsIgnoreCase(method)){
                bool = true;
                break;
            }
        }
        return bool;
    }

}
